package com.fingard.dsp.bank.directbank.citic03;

import com.fingard.constant.Format;
import com.fingard.dsp.bank.directbank.bankInterface.ITransaction;
import com.fingard.dsp.bank.reqrespobj.transaction.Req7515TodayTrans;
import com.fingard.dsp.bank.reqrespobj.transaction.Req7516HisTrans;
import com.fingard.dsp.bank.reqrespobj.transaction.RetAtsTrans;
import com.fingard.dsp.bank.reqrespobj.transaction.detail.RetAtsTransDetail;
import com.fingard.text.StringHelper;
import com.fingard.util.Digest;
import com.fingard.xml.XmlTextReader;
import com.fingard.xml.XmlTextWriter;

import java.util.Calendar;
import java.util.HashMap;

public class CITIC03Transaction extends CITIC03Base implements ITransaction {
    @Override
    public RetAtsTrans d_7516_HisTrans(Req7516HisTrans p_req7516) throws Exception {
        //历史明细查询返回ATS的对象
        RetAtsTrans retAts = new RetAtsTrans(p_req7516.reqHeader);
        String tmpRespCode = "";
        String tmpRespInfo = "";
        retAts.writeStart();//写返回ATS的统一头部信息
        try {
            CITIC03Header tmpBankHeader = new CITIC03Header();
            tmpBankHeader.action = "DLGSAQRY";

            int intPageNumber = 10;

            //tmpClndrStepTo.get(Calendar.MONTH) MONTH是从0开始编的，意味着0是1月，11是12月
            Calendar tmpCalendarFrom = Calendar.getInstance();
            tmpCalendarFrom.setTime(p_req7516.getDateFrom());
            tmpCalendarFrom.add(Calendar.DATE, 1);

            Calendar tmpCalendarTo = Calendar.getInstance();
            tmpCalendarTo.setTime(p_req7516.getDateTo());
            tmpCalendarTo.add(Calendar.DATE, 1);

            int tmpIntDateFrom = 0;
            int tmpIntDateTo = 0;
            int tmpDateIndex = 0;
            //按自然日循环查询
            while (tmpIntDateFrom <= tmpIntDateTo && tmpRespCode.length() == 0) {
                if (getBankConfig().getValueAsString("uniqueIDEnableDate").length() > 0 && Format.Date8Format.format(tmpCalendarFrom.getTime()).compareTo(getBankConfig().getValueAsString("uniqueIDEnableDate")) >= 0) {
                    tmpDateIndex = 0;
                }
                Calendar tmpClndrStepTo = Calendar.getInstance();
                tmpClndrStepTo.setTime(tmpCalendarFrom.getTime());

                int tmpNowStartRecord = 1;

                int tmpNowReadedCount = 0;


                HashMap<String, Integer> tmpDictTotalCount = new HashMap<String, Integer>();

                boolean tmpQryNext = true;
                while (tmpQryNext && tmpRespCode.length() == 0) {//分页查询
                    XmlTextWriter xmlWriter = new XmlTextWriter();//发银行报文的XML对象
                    //写入通用的头部节点
                    writeCommonHeader(xmlWriter, tmpBankHeader);
                    String specialAct = getBankConfig().getValueAsString("specialAct");
                    String accNo = p_req7516.actNum;
                    if (specialAct.contains("," + p_req7516.actNum + ",")) {
                        accNo = accNo + convertCurToBank(p_req7516.actCur);
                    }
                    xmlWriter.writeElementString("accNo", accNo);
                    xmlWriter.writeElementString("startDate", Format.Date8Format.format(tmpCalendarFrom.getTime()));
                    xmlWriter.writeElementString("endDate", Format.Date8Format.format(tmpCalendarFrom.getTime()));
                    xmlWriter.writeElementString("pageNumber", String.valueOf(intPageNumber));
                    xmlWriter.writeElementString("startRecord", String.valueOf(tmpNowStartRecord));
                    xmlWriter.writeElementString("cryType", convertCurToBank(p_req7516.actCur));
                    xmlWriter.writeEndDocument();
                    String[] tmpStrRet = sendToBank(xmlWriter.toXmlString());
                    XmlTextReader tmpBkReader;
                    if (tmpStrRet[0].length() == 0) {
                        StringBuilder tmpSbMsg = new StringBuilder();
                        tmpBkReader = loadBankRespXmlReader(tmpStrRet[1], tmpSbMsg);
                        if (tmpBkReader != null) {
                            String tmpStatus = tmpBkReader.getFirstText("/stream/status");
                            String tmpStatusText = tmpBkReader.getFirstText("/stream/statusText");
                            if (isActiveRetCode(tmpStatus)) {
                                int tmpTotalRocords = 0;
                                if (tmpBkReader.getFirstText("/stream/totalNum") != null && tmpBkReader.getFirstText("/stream/totalNum").trim().length() > 0) {
                                    tmpTotalRocords = Integer.parseInt(tmpBkReader.getFirstText("/stream/totalNum"));
                                }
                                int tmpEachPiCount = 0;
                                while (tmpBkReader.read("/stream/list/row")) {
                                    tmpEachPiCount++;
                                    tmpDateIndex++;
                                    RetAtsTransDetail tmpRetDetail = new RetAtsTransDetail();
                                    String creditDebitFlag = tmpBkReader.readedXElement.getSingleText("foreignDCFlag");//海外借贷标志 char(1) D：借，C：贷
                                    String tranAmount = tmpBkReader.readedXElement.getSingleText("tranAmt");
                                    tmpRetDetail.originator = tmpBkReader.readedXElement.getSingleText("stmtlistid").trim();
                                    String tranDate = tmpBkReader.readedXElement.getSingleText("valueDate");

                                    if (true) {
                                        if (creditDebitFlag != null) {
                                            if ("D".equals(creditDebitFlag)) //借贷标识
                                            {
                                            /*if (tranAmount.indexOf("-") >= 0) {
                                                tmpRetDetail.cdFlag = "2";
                                            } else {*/
                                                tmpRetDetail.cdFlag = "1";
                                                //}
                                            } else if ("C".equals(creditDebitFlag)) {
                                            /*if (tranAmount.indexOf("-") >= 0) {
                                                tmpRetDetail.cdFlag = "1";
                                            } else {*/
                                                tmpRetDetail.cdFlag = "2";
                                                //}
                                            } else {
                                                tmpRespCode = "-1";
                                                tmpRespInfo = "借贷标志( " + creditDebitFlag + ")无法识别，请与银行核对";
                                                break;
                                            }
                                        }
                                        tmpRetDetail.tranAmt = tranAmount;//.replace("-", "");
                                    } else {
                                        if (creditDebitFlag != null) {
                                            if ("D".equals(creditDebitFlag)) //借贷标识
                                            {
                                                if (tranAmount.indexOf("-") >= 0) {
                                                    tmpRetDetail.cdFlag = "2";
                                                } else {
                                                    tmpRetDetail.cdFlag = "1";
                                                }
                                            } else if ("C".equals(creditDebitFlag)) {
                                                if (tranAmount.indexOf("-") >= 0) {
                                                    tmpRetDetail.cdFlag = "1";
                                                } else {
                                                    tmpRetDetail.cdFlag = "2";
                                                }
                                            } else {
                                                tmpRespCode = "-1";
                                                tmpRespInfo = "借贷标志( " + creditDebitFlag + ")无法识别，请与银行核对";
                                                break;
                                            }
                                        }
                                        tmpRetDetail.tranAmt = tranAmount.replace("-", "");
                                    }

                                    String tranTime = "";
                                    String valueDate = tmpBkReader.readedXElement.getSingleText("valueDate");
                                    tmpRetDetail.tranDate = tranDate.substring(0, 4) + "-" + tranDate.substring(4, 6) + "-" + tranDate.substring(6, 8);
                                    if (StringHelper.hasAnyChar(tranTime)) {
                                        tmpRetDetail.tranTime = tmpRetDetail.tranDate + " " + tranTime.substring(0, 2) + ":" + tranTime.substring(2, 4) + ":" + tranTime.substring(4, 6);
                                    } else {
                                        tmpRetDetail.tranTime = tmpRetDetail.tranDate;
                                    }
                                    if (StringHelper.hasAnyChar(valueDate)) {
                                        tmpRetDetail.valueDate = valueDate.substring(0, 4) + "-" + valueDate.substring(4, 6) + "-" + valueDate.substring(6, 8);
                                    } else {
                                        tmpRetDetail.valueDate = tmpRetDetail.tranDate;
                                    }
                                    tmpRetDetail.busType = tmpBkReader.readedXElement.getSingleText("bsnCode");
                                    String memo = tmpBkReader.readedXElement.getSingleText("memo");
                                    if (memo.length() > 256) {
                                        tmpRetDetail.usage = memo.substring(0, 256);
                                        tmpRetDetail.payCode = memo.substring(256);
                                    } else {
                                        tmpRetDetail.usage = memo;
                                    }
                                    tmpRetDetail.cur = convertCurToATS(tmpBkReader.readedXElement.getSingleText("cryType"));
                                    if (StringHelper.isNullOrEmpty(tmpRetDetail.actNum)) {
                                        tmpRetDetail.actNum = p_req7516.actNum;
                                    }
                                    String uniqueID = tmpDateIndex + "@" + tmpBkReader.readedXElement.getSingleTextNotNull("stmtlistid") + "@" + tmpBkReader.readedXElement.getSingleTextNotNull("valueDate") + "@" + tmpBkReader.readedXElement.getSingleTextNotNull("bsnCode") + "@" + tmpBkReader.readedXElement.getSingleTextNotNull("cryType") + "@" + tmpBkReader.readedXElement.getSingleTextNotNull("tranAmt") + "@" + tmpBkReader.readedXElement.getSingleTextNotNull("foreignDCFlag") + "@" + tmpBkReader.readedXElement.getSingleTextNotNull("memo");
                                    tmpRetDetail.uniqueID = Digest.hmacSign(uniqueID);
                                    nodeAnalysic(tmpBkReader.readedXElement, tmpRetDetail, getCharset());
                                    retAts.writeRetDetail(tmpRetDetail);
                                }
                                //tmpGlobalCount += tmpEachPiCount;//全部已查数，仅统计
                                tmpNowReadedCount += tmpEachPiCount;//本次分页已查数
                                if (tmpNowReadedCount < tmpTotalRocords) {//查询下一页
                                    tmpNowStartRecord = tmpNowReadedCount + 1;//本次分页下页查询起始记录号
                                } else if (tmpNowReadedCount == tmpTotalRocords) {
                                    tmpQryNext = false;
                                } else {
                                    tmpQryNext = false;
                                    tmpRespCode = "-1";
                                    tmpRespInfo = "银行预期返回总数" + tmpTotalRocords + "条，实际读取" + tmpNowReadedCount + "条";
                                    break;
                                }
                            } else {
                                tmpQryNext = false;
                                tmpRespCode = "-1";
                                tmpRespInfo = StringHelper.isNullOrEmpty(tmpStatusText) ? tmpStatus : tmpStatusText;
                                break;
                            }
                        } else {
                            tmpQryNext = false;
                            tmpRespCode = "-1";
                            tmpRespInfo = tmpSbMsg.toString();
                            break;
                        }
                    } else {
                        tmpQryNext = false;
                        tmpRespCode = "-1";
                        tmpRespInfo = tmpStrRet[1];
                        tmpQryNext = false;
                        break;
                    }
                }
                tmpCalendarFrom = tmpClndrStepTo;
                tmpCalendarFrom.add(Calendar.DATE, 1);
                tmpIntDateFrom = Integer.parseInt(Format.Date8Format.format(tmpCalendarFrom.getTime()));
                tmpIntDateTo = Integer.parseInt(Format.Date8Format.format(tmpCalendarTo.getTime()));
            }
        } catch (Exception e) {
            tmpRespCode = "-1";
            tmpRespInfo = e.getMessage();
            e.printStackTrace();
        }
        if (tmpRespCode.equals("-1")) {
            retAts = new RetAtsTrans(p_req7516.reqHeader);
            retAts.writeStart();//写返回ATS的统一头部信息
            retAts.writeRespCode(tmpRespCode);
            retAts.writeRespInfo(tmpRespInfo);
        } else if (retAts.getWrittenRdCount() == 0) {
            retAts.writeRespCode("0");
            retAts.writeRespInfo("交易为空");
        }
        retAts.writeEnd();
        return retAts;
    }

    @Override
    public RetAtsTrans d_7515_TodayTrans(Req7515TodayTrans p_req7515) throws Exception {
        return null;
    }
}
